<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page import="cn.edu.nju.ws.aquila.query.Argument,cn.edu.nju.ws.aquila.query.Query,cn.edu.nju.ws.aquila.query.Relation,cn.edu.nju.ws.aquila.query.Pair,cn.edu.nju.ws.aquila.query.InstantQuery,cn.edu.nju.ws.aquila.reasoning.Constant,cn.edu.nju.ws.aquila.reasoning.KnowledgeBase,cn.edu.nju.ws.aquila.reasoning.GroundAtom" %>
<%@page import="java.util.ArrayList,java.util.HashSet,cn.edu.nju.ws.aquila.rdf.Literal,cn.edu.nju.ws.aquila.rdf.BlankNode" %>
<%@page import="cn.edu.nju.ws.aquila.rdf.Resource,cn.edu.nju.ws.aquila.rdf.URIResource,java.net.URLEncoder" %>
<%@page import="cn.edu.nju.ws.aquila.query.Linkquery,cn.edu.nju.ws.aquila.util.QueryUtil,java.util.HashMap,cn.edu.nju.ws.aquila.query.Pair"%>
<%@page import="cn.edu.nju.ws.aquila.index.QueryIndex,cn.edu.nju.ws.aquila.recommendation.QueryRecommendation"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Query Answers</title>
<link rel="stylesheet" type="text/css" href="css/answer.css" />
<link rel="stylesheet" type="text/css" href="css/flexigrid.css" />
<script type="text/javascript" src="script/jquery.js"></script>
<script type="text/javascript" src="script/answer.js"></script>	
<script type="text/javascript" src="script/flexigrid.js"></script>	
</head>
<body>
<%

String type=null;
if(session.getAttribute("type")==null){
	response.sendRedirect("index.jsp") ;
	return;
}
else
	type = (String)session.getAttribute("type");
String title=null;
if(session.getAttribute("title")==null){
	response.sendRedirect("index.jsp") ;
	return;
}
else
	title = (String)session.getAttribute("title");
Query query = null;
if(session.getAttribute("query")==null){
	response.sendRedirect("index.jsp") ;
	return;
}
else
	query = (Query)session.getAttribute("query");
int queryId = Query.getQueryIdByNameAuthor(query.getName(),query.getAuthor()) ;
ArrayList<Constant> arguments  = null;
if(session.getAttribute("arguments")==null){
	response.sendRedirect("index.jsp") ;
	return;
}
else
	arguments = (ArrayList<Constant>)session.getAttribute("arguments");
ArrayList<Integer> showList =  query.getShowArgsList() ;
int colNum = showList.size();
//为后面调用浏览链接查询做准备
int currentInstId = 0;
%>
		<div id="top">
			<div class="nav"><a href="index.jsp">Go to Aquila</a></div>
		</div>
		<div id="main">
		    <div id="left">
		    	<div class='title'>Query</div>
		    	<div id="queryTitle"><%=title %></div>
		    	<div class='title'>Answers</div>
		    	
		      <div id="relation_table" class="relation_table " style="position:relative">
<%      
       KnowledgeBase kb = new KnowledgeBase(null,null);
       HashSet<GroundAtom> result  =null;
       InstantQuery instQuery = null;
       if(type.equals("tmpt")){
    	  result =  kb.Evaluate(query,arguments) ;
    	  //index instantiated query
    	  instQuery = new InstantQuery(query,arguments);
    	  instQuery.serialize();
    	  currentInstId = instQuery.getInstantQueryId() ;
    	  QueryIndex.getInstance().pushURI(QueryIndex.InstPrefix+currentInstId);
       }else{
    	   instQuery= (InstantQuery)query;
    	   result = kb.Evaluate(instQuery.getDependentQuery(),arguments);
    	   instQuery.serialize();
    	   currentInstId = instQuery.getInstantQueryId() ;
       }
	   Pair info  = query.getRelation();
 	  ArrayList<Argument>  relationArgs = Relation.getArgumentsByReId(Relation.getRelationIdByNameAuthor(info.getContent(),info.getAuthor()));
%>
             <table id="answerTable" >
             	 <thead>
             	   <tr>
             	   <% for(int i=0;i<colNum;i++){ 
             	      String field = "arg"+i;
                      String relationArgName = relationArgs.get(i).getName();
             	   %>
                     <th field='<%=field%>'>
                      <span><%=relationArgName %></span> 
                     </th>
                    <%} %>
                 </tr>
               </thead>
               <tbody> 
                  <% for(GroundAtom fact:result) {%>
                       <tr>
                       
                     
                  <%   
                  //没有去重
                  for(int index = 0;index<showList.size();index++){
                            Constant mconst =fact.get(index) ;
                            Resource resource  = mconst.getResource();
                            if(resource instanceof Literal){
                            	String content = ((Literal)resource).getLexicalForm();
                  %>
                   <td >
                   <%=content %>
                   </td>
                   <%
                   //blanknode 不给它继续浏览的机会
                   }else if(resource instanceof BlankNode){ 
                             String content = ((BlankNode)resource).getLabel();
                  %>
                     <td >
                       <%=content %>
                     </td>
                   <%}else{
                	   URIResource uriResource = (URIResource)resource;
 	 	  			   String ovalue = uriResource.getURI();
 	 	  			   String olabel = uriResource.getLabel();	
 	 	  			   String encodeVal = URLEncoder.encode(ovalue) ;
                	%>
                	<td>
                	  <a href='browse_ui.jsp?id=<%=queryId%>&uri=<%=encodeVal%>' title='<%=ovalue%>'><%=olabel%></a>
                	</td>
                	<%}}%>
                  </tr>  
                <% } %>
                    
              
               </tbody>           	  
             </table>
		      </div>		    	
		    </div>	
		   <!-- 没有考虑推荐的查询要与链接查询去重 -->
		<div id="recomd">
			 <div class='title'>Link queries</div>			
		   <div id='linkList'>
		   	  <ol>
		 <% 
           ArrayList<Linkquery>	 linkQueries = query.getLinkQueries() ;
           for(int i=0;i<linkQueries.size();i++){
        	   Linkquery linkquery = linkQueries.get(i) ;
        	   HashMap<Integer,Constant> constMap =  linkquery.getConstantInfo() ;
        	   HashMap<Integer,Integer> varMap = linkquery.getLinkRelationShip();
        	   Pair linkInfo = linkquery.getQueryName();
        	   int linkqId = Query.getQueryIdByNameAuthor(linkInfo.getContent(),linkInfo.getAuthor());
        	   Query linkq = Query.getQueryById(linkqId) ;
        	   String titleRaw = linkq.getTitle();
        	   ArrayList<Constant> linkArguments = new ArrayList<Constant>();
        	   int num = linkq.getAllArguments().size();
        	   for(int j=0;j<num;j++){
        		   if(constMap.keySet().contains(j)){
        			   Constant mconst = constMap.get(j) ;
        			   linkArguments.add(mconst) ;
        		   }else{
        			   linkArguments.add(arguments.get(varMap.get(j)));
        		   }
        	  }
        	   String linkqTitle = QueryUtil.instantiateTitle(titleRaw,linkArguments);
        	   String href = "answer?type=linkq&id="+linkqId+"&instId="+currentInstId;
        %>	
		   	  	<li><a href="<%=href%>" title="<%=linkqTitle%>"><%=linkqTitle %></a></li>
		 <%} %>
		   	  </ol>
		   	</div>
		</div>
		</div>
		    <div id="right">
		    	<div class='title'>Related queries</div>
		    	<div id='recommendList'>
		    <%
		    	QueryRecommendation queryRecommendation = new QueryRecommendation(instQuery);
		        ArrayList<InstantQuery> recommendList = queryRecommendation.getRecommendedQueries(10);
		    %>
		   	  <ol>
		   	  <%  for(int i=0;i<recommendList.size();i++) {
		   	           InstantQuery recommendInstQuery = recommendList.get(i) ;
		   	           int recommendId =recommendInstQuery.getInstantQueryId();
		   	           ArrayList<Constant> recomdArguments = recommendInstQuery.getValues();
		   	           String titleRaw = recommendInstQuery.getTitle();
		   	           String recommendTitle = QueryUtil.instantiateTitle(titleRaw,recomdArguments) ;
		   	           String href="answer?type=inst&id="+recommendId;
		   	  %> 
		   	  	<li><a href="<%=href%>" title="<%=recommendTitle%>"><%=recommendTitle %></a></li>
		   	  <%} %>
		   	  </ol>
		   	</div>
		   	</div>
</body>
</html>